const timeTool = require('./time');
const { BaseError } = require('../error/base');
const routerError = require('../error/routererror');

function routeWrapper (genFn, needAuth = false) {
    // 套娃第一层
    return (req, res, next) => {
        // 校验Token
        if (needAuth) {
            if (!req.auth) {
                res.send(makeErrorReturn(new routerError.RouterTokenError('未登陆授权')));
                return;
            }
        }
        // 套娃第二层
        genFn(req, res, next)
            // 套娃第三层
            .then((data) => {
                // 处理正常业务请求
                // 套娃最终执行
                if (data !== undefined) {
                    res.send(makeSuccessReturn(data));
                }
            }).catch((error) => {
                if (error instanceof BaseError) {
                // 处理自定义异常情况
                    res.send(makeErrorReturn(error));
                } else {
                // 除此以外直接抛出
                    res.send(makeErrorReturn(new BaseError(error.message)));
                }
            });
    };
}

// const routeWrapper = fn => (...args) => makeSuccessReturn(args[1], fn(...args).catch(args[2]));

function makeErrorReturn (errorInstance) {
    let errorType = errorInstance.constructor.name;
    let errorMsg = errorInstance.errmsg === undefined ? 'Unknown Error' : errorInstance.errmsg;
    return {
        status: 'fail',
        timestamp: timeTool.getCurrentTimestamp(),
        errcode: errorType,
        errmsg: errorMsg
    };
}

function makeSuccessReturn (data) {
    return {
        status: 'success',
        timestamp: timeTool.getCurrentTimestamp(),
        data: data
    };
}

module.exports = {
    routeWrapper,
    makeErrorReturn
};
